import React, { useEffect, FC, memo } from 'react';
// import styles from './index.less';
import useHoxModel from '../../useHoxModel';
import TreeComponent from '@/components/TreeComponent';
import { updateTreeDataProps } from '@/components/TreeComponent';
import { DataNode } from 'antd/lib/tree';
import Spin from 'antd/es/spin';

interface TreeProps {}
const Tree: FC<TreeProps> = ({}) => {
  const {
    getAreaList,
    selectedKeys = [],
    areaList = [],
    dispatch,
    firstGetAreaList,
    getAreaListLoading,
  } = useHoxModel((model) => [model.areaList, model.getAreaListLoading, model.selectedKeys]);
  useEffect(() => {
    firstGetAreaList();
  }, []);

  const updateTreeData = async (key: string | number, updateTreeData: updateTreeDataProps) => {
    let res = await getAreaList({ id: Number(key) });
    if (res.result === 0) {
      const newAreaList = updateTreeData(
        areaList,
        key,
        res?.data.map((item: any) => {
          return {
            key: item.id.toString(),
            title: item.name,
            isLeaf: item.isRegion,
            code: item.code,
          };
        }) || [],
      );
      dispatch({ areaList: newAreaList });
    }
  };
  return (
    <Spin spinning={getAreaListLoading}>
      <TreeComponent
        onSelect={(record, { selected, selectedNodes }) => {
          if (!selected) return;

          const item: DataNode & { code?: string } = selectedNodes[0];
          dispatch({ selectedKeys: [item.key as string], currentCode: item.code });
        }}
        selectedKeys={selectedKeys}
        treeData={areaList || []}
        updateData={updateTreeData}
      />
    </Spin>
  );
};

export default memo(Tree);
